package com.hschinese.pronunciation.widget;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.bean.AppDataBean;
import com.hschinese.pronunciation.bean.AppResourceMap;
import com.hschinese.pronunciation.bean.Type14Bean;
import com.hschinese.pronunciation.db.DBHelper;
import com.hschinese.pronunciation.interfaces.LessonProgressInterface;
import com.hschinese.pronunciation.interfaces.NextLessonInterface;
import com.hschinese.pronunciation.interfaces.PlayClickListener;
import com.hschinese.pronunciation.interfaces.PlayCompleteListener;
import com.hschinese.pronunciation.interfaces.RecordStatusListener;
import com.hschinese.pronunciation.interfaces.VolumeListener;
import com.hschinese.pronunciation.utils.AnimatorUtil;
import com.hschinese.pronunciation.utils.HsSoundUtil;
import com.hschinese.pronunciation.utils.Logger;
import com.hschinese.pronunciation.utils.SimpleRecordUtil;
import com.hschinese.pronunciation.utils.Utils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by wo on 2015/11/5.
 */
public class StudyRecognitionView extends LinearLayout {

    @Bind(R.id.rl_contstrction_parient)
    RelativeLayout rlContstrctionParient;
    @Bind(R.id.tv_study_recognition_pinyin)
    TextView tvStudyRecognitionPinyin;
    @Bind(R.id.tv_study_recognition_hanzi)
    TextView tvStudyRecognitionHanzi;
    @Bind(R.id.iv_recognition_back)
    ImageView ivRecognitionBack;
    @Bind(R.id.tv_recognition_text)
    TextView tvRecognitionText;
    @Bind(R.id.practise_play_control)
    PlayControlView practisePlayControl;
    @Bind(R.id.rl_practise_play_control)
    RelativeLayout rlPractisePlayControl;
    private Activity mContext = null;
    private View mView = null;
    private Cursor cursor;
    private ViewGroup anim_mask_layout;//动画层
    private int lessonType = 0;
    private int weithLess = 0;
    private int currentPosition = 0;
    private int groupID = 0;
    private List<AppDataBean> mDataList;
    private List<Integer> picLists;
    private List<Type14Bean> mIsDoing;

    Set setDown = new HashSet();
    private LessonProgressInterface mListener = null;
    private NextLessonInterface mNextListener = null;
    private String mMp3SourceDir = null;
    private boolean isFirst = true;
    private int bg1Id, bg2id;
    private AlphaAnimation alphaAnimation1;
    private TranslateAnimation alphaAnimation2;
    private boolean isFrash=true;
    /**
     *
     */
    private static final int MESSAGE_LOGIN = 1;
    Handler   handler = new Handler(new Handler.Callback(){
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.what == MESSAGE_LOGIN ){

                tvStudyRecognitionPinyin.setVisibility(VISIBLE);
                tvRecognitionText.setVisibility(VISIBLE);
            }
            return true;
        }
    });
    private boolean aBoolean;
    private Type14Bean type14Bean;

    public StudyRecognitionView(Context context) {
        super(context);
        initViews(context);
    }

    public StudyRecognitionView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);
    }
    public void setVolumeListener(VolumeListener l) { practisePlayControl.setVolumeListener(l); }

    public void setRecordListener(RecordStatusListener l) { practisePlayControl.setRecordListener(l); }
    private void initViews(Context context) {
        mContext = (Activity) context;
        mView = LayoutInflater.from(context).inflate(R.layout.study_recognition_view, null);
        ButterKnife.bind(this, mView);
        this.addView(mView);
    }

    public void setCurrentPosition(int pos) {
        currentPosition = pos;
    }

    public void initData() {
        mDataList = new ArrayList<AppDataBean>();
        mIsDoing = new ArrayList<>();
       // cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=? ", new String[]{lessonType + ""});
        cursor = DBHelper.getInstance(mContext).query(DBHelper.RES_TABLE, " type=?  and groupID=?", new String[]{lessonType + "", groupID + ""});
        mDataList.clear();
        mIsDoing.clear();
        if (cursor != null)
            Logger.e("xionghy-cursor: " + cursor.getCount());
        while (cursor.moveToNext()) {
            AppDataBean d = new AppDataBean();
            Type14Bean type14Bean = new Type14Bean();
            d.setChinese(cursor.getString(cursor.getColumnIndex("chinese")));
            d.setPinyin(cursor.getString(cursor.getColumnIndex("pinyin")));
            d.setPhone(cursor.getString(cursor.getColumnIndex("phone")));
            d.setTone(cursor.getString(cursor.getColumnIndex("tone")));
            d.setAudioName(cursor.getString(cursor.getColumnIndex("audioName")));
            d.setPicName(cursor.getString(cursor.getColumnIndex("picName")));
            d.setType(cursor.getInt(cursor.getColumnIndex("type")));
            d.setGroupID(cursor.getInt(cursor.getColumnIndex("groupId")));
            d.setWeight(cursor.getInt(cursor.getColumnIndex("weight")));
            mDataList.add(d);
            mIsDoing.add(type14Bean);
        }
        if (mDataList.size() <= 0) {
            Logger.e("获取到的数据为空。。。。");
            return;
        }
        Logger.e("xionghy - " + mDataList.size());
        Logger.e("xionghy: " + mDataList.get(currentPosition).toString());
        updateViewData();
    }

    private void updateViewData() {
        if (mListener != null) {
            mListener.setProgress(mDataList.size(), currentPosition);
        }
        AppDataBean data = mDataList.get(currentPosition);
        mMp3SourceDir = AppResourceMap.getMp3Fold(lessonType) + data.getAudioName().replace("|", "") + ".mp3";
        tvStudyRecognitionPinyin.setText(data.getPinyin());
        tvStudyRecognitionHanzi.setText(data.getChinese());
        practisePlayControl.setStandardUrl(mMp3SourceDir);
        type14Bean = mIsDoing.get(currentPosition);
        if(type14Bean.isDoing()){
            practisePlayControl.setPlayRecordVisibility(View.VISIBLE);
            ivRecognitionBack.setVisibility(VISIBLE);
            tvStudyRecognitionPinyin.setVisibility(VISIBLE);
            tvRecognitionText.setVisibility(VISIBLE);
        }else {
            practisePlayControl.setPlayRecordVisibility(View.INVISIBLE);
            ivRecognitionBack.setVisibility(INVISIBLE);
            tvStudyRecognitionPinyin.setVisibility(INVISIBLE);
            tvRecognitionText.setVisibility(INVISIBLE);
            isFrash=true;

            practisePlayControl.setPlayanim(true);
        }

        addAnimation();
        practisePlayControl.setPlayClickListener(new PlayClickListener() {
            @Override
            public void onPlayClicked(boolean isPlaying) {
                practisePlayControl.setPlayanim(false);
                practisePlayControl.setVoanim(true);
                type14Bean.setDoing(true);
                if(isFrash){
                    scaleIn2();

                    handler.sendEmptyMessageDelayed(MESSAGE_LOGIN,1000);
                    isFrash=false;
                }else {
                    isFrash=false;
                }


            }
        });


    }

    private void setImageAnimi() {
    }

    public void setLessonType(int type) {
        lessonType = type;

    }

    public void setWeithLesson(int weithLesson) {
        this.weithLess = weithLesson;
        SimpleRecordUtil.getInstance(mContext).setPlayCompleteListener(new PlayCompleteListener() {
            @Override
            public void playComplete() {

            }
        });
    }

    public void nextWord() {
        // TODO 数据切换，涉及到界面上文字和图片的切换
        practisePlayControl.resetProgressBar();

        currentPosition++;
        if (currentPosition < mDataList.size()) {
            updateViewData();

        } else {
            if(groupID==3){
                Utils.showDialog(mContext, R.string.next_lesson_dialog_msg, lessonType, mNextListener);
            }else {

                groupID++;
                currentPosition=0;
                initData();
            }
        }
    }


    private void startTask(float t, final AnimationDrawable draw) {
        if (draw == null) return;
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                draw.stop();
            }
        }, (int) (t * 1000));
    }

    public void beforeWord() {
        practisePlayControl.resetProgressBar();
        if (currentPosition <= 0 && groupID==0){

        }else {
            if(currentPosition==0){
                groupID--;
                currentPosition=0;
                initData();
            }else {
                currentPosition--;
                updateViewData();
            }


        }

    }

    public void setListener(LessonProgressInterface listener) {
        mListener = listener;
    }

    public void setNextListener(NextLessonInterface listener) {
        mNextListener = listener;
    }

    private List<Integer> getPicName(String str) {
        picLists.clear();
        if (!str.equals("") || str.equals("null")) {
            String tones[] = str.replace("|", " ").split(" ");
            for (int i = 0; i < tones.length; i++) {
                picLists.add(getResource(tones[i]));
            }

        }
        return picLists;
    }

    public int getResource(String imageName) {
        Context ctx = mContext.getBaseContext();
        int resId = getResources().getIdentifier(imageName, "drawable", ctx.getPackageName());
        return resId;
    }


    private void checkResult(TextView view, boolean isTrue, int tone) {

        if (isTrue) {
            HsSoundUtil.play(mContext, R.raw.right);
            // TODO 设置当前选择正确的标识
            if (tone == 1) {


            } else if (tone == 2) {


            } else if (tone == 3) {


            }


            AnimatorUtil.pluseAnimator(mContext, view);
        } else {
            // TODO 设置成错误的颜色
            HsSoundUtil.play(mContext, R.raw.wrong);


            AnimatorUtil.shakeAnimator(mContext, view);

        }
    }

    public void onDestroy() {


        if (cursor != null)
            cursor.close();
    }


    private void resetFirstToneImg(int number) {


    }

    // 每个空间都添加一种动画
    long durationMillis = 1000, delayMillis = 0;
    private Animation chooseViewAnimation = null;
    private Animation.AnimationListener wordViewAnimListener = null;

    private void addAnimation() {
        if (rlContstrctionParient != null) {
            wordViewAnimListener = new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {


                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            };
            chooseViewAnimation = scaleIn(rlContstrctionParient, durationMillis, delayMillis, wordViewAnimListener);
            rlContstrctionParient.post(new Runnable() {
                @Override
                public void run() {
                    chooseViewAnimation.start();

                }
            });

        }
    }

    private Animation scaleIn(View view, long durationMillis, long delayMillis, Animation.AnimationListener l) {
        ScaleAnimation animation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(durationMillis);
        animation.setStartOffset(delayMillis);
        view.setVisibility(View.VISIBLE);
        view.startAnimation(animation);
        animation.setAnimationListener(l);
        animation.cancel();
        return animation;
    }
    private void scaleIn2() {
        ScaleAnimation animation = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(durationMillis);
        animation.setStartOffset(delayMillis);
        ivRecognitionBack.setVisibility(View.VISIBLE);
        ivRecognitionBack.startAnimation(animation);
        animation.setAnimationListener(wordViewAnimListener);
        animation.cancel();
        animation.start();

    }

    public void setGroupId(int groupID) {
        this.groupID=groupID;
    }
}
